<template>
	<div class="login-wrapper" id="loginBackground">
		<el-card class="box-card">
			<div class="form-wrapper">
				<h1 class="login-title">登录</h1>
				<p class="login-system">{{ $config.siteName }}</p>
				<!-- 登录表单开始 -->
				<el-form
					class="login-form"
					ref="loginForm"
					:model="loginForm"
					:rules="loginFormRules"
					label-width="100px"
					hide-required-asterisk
				>
					<el-form-item prop="username">
						<el-input
							prefix-icon="el-icon-user"
							v-model="loginForm.username"
							placeholder="用户名"
							maxlength="20"
						/>
					</el-form-item>
					<el-form-item prop="password">
						<el-input
							prefix-icon="el-icon-lock"
							v-model="loginForm.password"
							placeholder="密码"
							show-password
							maxlength="20"
						/>
					</el-form-item>
					<el-form-item
						prop="verifyCode"
						style="width: 100%"
						v-if="this.captchaMode"
					>
						<el-input
							prefix-icon="Picture"
							v-model="loginForm.verifyCode"
							placeholder="验证码"
							style="width: 55%"
						/>
						<div class="login-code">
							<img :src="codeUrl" @click="getCode" class="login-code-img" />
						</div>
					</el-form-item>
					<div style="float: left">
						<el-checkbox
							v-model="loginForm.rememberMe"
							style="margin: 0px 0px 25px 1px"
							>记住密码
						</el-checkbox>
					</div>
					<el-form-item class="login-btn-form-item">
						<el-button
							class="login-btn"
							type="primary"
							:disabled="loginBtnDisabled"
							:loading="loginBtnLoading"
							@click="submitForm('loginForm')"
						>
							<span v-if="!loginBtnLoading">登 录</span>
							<span v-else>登 录 中...</span>
						</el-button>
					</el-form-item>
				</el-form>
				<!-- 登录表单结束 -->
			</div>
		</el-card>
	</div>
</template>

<script>
import CanvasNest from 'canvas-nest.js'
import Cookies from 'js-cookie'
import * as loginApi from '@/api/loginApi'

// 背景配置
const config = {
	// 线条颜色
	color: '64, 158, 255',
	// 节点颜色
	pointColor: '64, 158, 255',
	// 线条透明度
	opacity: 0.5,
	// 线条数量
	count: 99,
	// 画面层级
	zIndex: -1
}

export default {
	name: 'MyLogin',

	data() {
		return {
			codeUrl: '',
			loading: false,
			captchaMode: false,
			// 登录表单数据
			loginForm: {
				username: '',
				password: '',
				rememberMe: false,
				verifyCode: '',
				verifyCodeUUID: ''
			},
			// 登录表单验证规则
			loginFormRules: {
				username: [
					{ required: true, message: '请输入用户名', trigger: 'blur' },
					{ max: 20, message: '不能超过 20 个字符', trigger: 'blur' }
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }

        ],
				verifyCode: [
					{ required: true, message: '请输入验证码', trigger: 'change' }
				]
			},
			// 登录按钮是否禁用
			loginBtnDisabled: false,
			// 登录按钮是否loading状态
			loginBtnLoading: false
		}
	},
	computed: {
		url() {
			let _url = this.$route.query.Rurl //  获取路由前置守卫中 next 函数的参数，即登录后要去的页面
			return _url
				? { path: _url }
				: { name: 'File', query: { fileType: 0, filePath: '/' } } //  若登录之前有页面，则登录后仍然进入该页面
		},
		// 屏幕宽度
		screenWidth() {
			return this.$store.state.common.screenWidth
		}
	},
	created() {
		this.getCookie()
		this.getCaptchaMode()
		//  绘制背景图
		this.$nextTick(() => {
			let element = document.getElementById('loginBackground')
			new CanvasNest(element, config)
		})
	},
	mounted() {
		if (this.screenWidth <= 768) {
			this.loginBtnDisabled = false
		}
	},
	methods: {
		/**
		 * 获得Cookie
		 */
		getCookie() {
			const username = Cookies.get('username')
			const password = Cookies.get('password')
			const rememberMe = Cookies.get('rememberMe')
			this.loginForm = {
				username: username === undefined ? this.loginForm.username : username,
				password: password === undefined ? this.loginForm.password : password,
				rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
			}
		},

		/**
		 * 查询是否开启验证码
		 */
		getCaptchaMode() {
			loginApi.getCaptchaMode().then((res) => {
				if (res.success) {
					this.captchaMode = res.data
				} else {
					this.$notify.error(res.message)
				}
			})
			if (this.captchaMode === true) {
				this.getCode()
			}
		},

		/**
		 * 获得验证码
		 */
		getCode() {
			loginApi.getCodeImg().then((res) => {
				if (res.success) {
					console.log('--------------开启验证码--------------')
					this.codeUrl = res.data.imgBase64
					this.loginForm.verifyCodeUUID = res.data.uuid
				} else {
					this.$notify.error(res.message)
				}
			})
		},

		/**
		 * 登录按钮点击事件 表单验证&用户登录
		 * @param {boolean} formName 表单ref值
		 */
		submitForm(formName) {
			this.loginBtnLoading = true
			this.$refs[formName].validate((valid) => {
				if (valid) {
					// 表单各项校验通过
					this.handleUserLogin(formName)
				} else {
					this.$notify.error('请完善信息！')
					return false
				}
			})
		},

		/**
		 * 用户登录
		 */
		handleUserLogin(formName) {
			// 勾选了需要记住密码设置在cookie中设置记住用户名和密码
			if (this.loginForm.rememberMe) {
				Cookies.set('username', this.loginForm.username, { expires: 30 })
				Cookies.set('password', this.loginForm.password, { expires: 30 })
				Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
			} else {
				// 否则移除
				Cookies.remove('username')
				Cookies.remove('password')
				Cookies.remove('rememberMe')
			}
			let username = this.loginForm.username.trim()
			const { password, verifyCode, verifyCodeUUID } = this.loginForm
			loginApi
				.login(username, password, verifyCode, verifyCodeUUID)
				.then((res) => {
					this.loginBtnLoading = false
					if (res.success) {
						// 存储token
						this.$store.commit('SET_TOKEN', res.data.tokenValue)
						// 存储用户id
						this.$store.commit('SET_LOGIN_ID', res.data.loginId)
						// 存储登录状态
						this.$store.commit('SET_IS_LOGIN', true)
						// 清空表单
						this.$refs[formName].resetFields()
						// 跳转到前一个页面或者网盘主页
						console.log(
							'----------------跳转到前一个页面或者网盘主页----------------'
						)
						this.$router.replace(this.url)
						this.$notify.success('登录成功')
					} else {
						this.$notify.error(res.message)
					}
				})
				.catch(() => {
					this.loginBtnLoading = false
				})
		}
	}
}
</script>
<style lang="stylus" scoped>
.box-card {
  height: 550px;
  width: 480px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2), 0 10px 10px rgba(0, 0, 0, 0.2);
  border-radius: 5%;
}

.login-wrapper {
  justify-content: center;
  align-items: center;
  // height: 500px !important;
  min-height: calc(100vh - 164px) !important;
  padding-top: 50px;

  .form-wrapper {
    width: 375px;
    margin: 0 auto;
    text-align: center;

    .login-title {
      margin-top 20px
      padding: 20px 0;
      font-weight: 300;
      font-size: 30px;
      color: #000;
    }

    .login-system {
      padding: 10px 0;
      font-weight: 300;
      color: #999;
    }

    .login-form {
      width: 100%;
      margin-top: 20px;

      .el-form-item {
        padding: 10px 0
      }

      >>> .el-form-item__content {
        margin-left: 0 !important;
      }

      & >>> .el-input__inner {
        font-size: 16px;
      }

      .login-btn-form-item {
        .login-btn {
          width: 100%;
        }

        & >>> .el-button {
          padding: 10px 90px;
          font-size: 16px;
        }
      }
    }

    .tip {
      width: 70%;
      margin-left: 86px;
    }
  }
}
</style>
